package com.example.module_hp_white_noise;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.example.module_hp_white_noise.base.BaseMvvmFragment;
import com.example.module_hp_white_noise.base.BaseViewModel;


import com.example.module_hp_white_noise.activity.HpWhiteNoiseChildPlayActivity;
import com.example.module_hp_white_noise.adapter.HpViewPageAdapter;
import com.example.module_hp_white_noise.databinding.FragmentHpWhiteNoiseMainBinding;
import com.example.module_hp_white_noise.entity.Music;
import com.example.module_hp_white_noise.fragment.HpWhiteNoiseFragment1;
import com.example.module_hp_white_noise.fragment.HpWhiteNoiseFragment2;
import com.example.module_hp_white_noise.fragment.HpWhiteNoiseFragment3;
import com.example.module_hp_white_noise.fragment.HpWhiteNoiseFragment4;
import com.example.module_hp_white_noise.service.MusicService;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;

import static android.content.Context.BIND_AUTO_CREATE;

@Route(path = "/hpWhiteNoise/route/HpWhiteNoiseMainFragment")
public class HpWhiteNoiseMainFragment extends BaseMvvmFragment<FragmentHpWhiteNoiseMainBinding, BaseViewModel> {
    List<String> titles=new ArrayList<>();
    List<Fragment> fragments=new ArrayList<>();
    @Override
    protected int initLayout() {
        return R.layout.fragment_hp_white_noise_main;
    }

    @Override
    protected int initBR() {
        return 0;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        //添加标题
        titles.add("白噪音");
        titles.add("舒适");
        titles.add("声音");
        titles.add("冥想");
        //添加Fragment进去
        fragments.add(new HpWhiteNoiseFragment1());
        fragments.add(new HpWhiteNoiseFragment2());
        fragments.add(new HpWhiteNoiseFragment3());
        fragments.add(new HpWhiteNoiseFragment4());
        //实例化适配器
        HpViewPageAdapter myAdapter=new HpViewPageAdapter(getChildFragmentManager(),getLifecycle(),fragments);
        //设置适配器
        binding.myViewPager.setAdapter(myAdapter);
        //TabLayout和Viewpager2进行关联
        new TabLayoutMediator(binding.myTabLayout, binding.myViewPager, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(titles.get(position));
            }
        }).attach();
        // 绑定service
        Intent i = new Intent(mContext, MusicService.class);
        mContext.bindService(i, mServiceConnection, BIND_AUTO_CREATE);
        // 小图标点击事件
        binding.playingLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                navigateTo(HpWhiteNoiseChildPlayActivity.class);
            }
        });
    }
    //切换viewpage
    public void setViewPageItem(int item){
        binding.myViewPager.setCurrentItem(item);
    }

    //设置当前播放
    private MusicService.MusicServiceBinder serviceBinder;
    // 定义与服务的连接的匿名类
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        // 绑定成功时调用
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            // 绑定成功后，取得MusicSercice提供的接口
            serviceBinder = (MusicService.MusicServiceBinder) service;

            // 注册监听器
            serviceBinder.registerOnStateChangeListener(listenr);

            Music item = serviceBinder.getCurrentMusic();

            /*if (serviceBinder.isPlaying()){
                // 如果正在播放音乐, 更新控制栏信息
                btnPlayOrPause.setImageResource(R.drawable.zanting);
                playingTitleView.setText(item.title);
                playingArtistView.setText(item.artist);
                if (item.isOnlineMusic){
                    Glide.with(getApplicationContext())
                            .load(item.imgUrl)
                            .placeholder(R.drawable.defult_music_img)
                            .error(R.drawable.defult_music_img)
                            .into(playingImgView);
                }
                else {
                    ContentResolver resolver = getContentResolver();
                    Bitmap img = Utils.getLocalMusicBmp(resolver, item.imgUrl);
                    Glide.with(getApplicationContext())
                            .load(img)
                            .placeholder(R.drawable.defult_music_img)
                            .error(R.drawable.defult_music_img)
                            .into(playingImgView);
                }
            }
            else if (item != null){
                // 当前有可播放音乐但没有播放
                btnPlayOrPause.setImageResource(R.drawable.bofang);
                playingTitleView.setText(item.title);
                playingArtistView.setText(item.artist);
                if (item.isOnlineMusic){
                    Glide.with(getApplicationContext())
                            .load(item.imgUrl)
                            .placeholder(R.drawable.defult_music_img)
                            .error(R.drawable.defult_music_img)
                            .into(playingImgView);
                }
                else {
                    ContentResolver resolver = getContentResolver();
                    Bitmap img = Utils.getLocalMusicBmp(resolver, item.imgUrl);
                    Glide.with(getApplicationContext())
                            .load(img)
                            .placeholder(R.drawable.defult_music_img)
                            .error(R.drawable.defult_music_img)
                            .into(playingImgView);
                }
            }*/
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 断开连接时注销监听器
            serviceBinder.unregisterOnStateChangeListener(listenr);
        }
    };

    // 实现监听器监听MusicService的变化，
    private MusicService.OnStateChangeListenr listenr = new MusicService.OnStateChangeListenr() {

        @Override
        public void onPlayProgressChange(long played, long duration) {}

        @Override
        public void onPlay(Music item) {
            int thisImgUrl = mContext.getResources().getIdentifier(item.imgUrl,"drawable",mContext.getPackageName());
            binding.playingLl.setVisibility(View.VISIBLE);
            Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.music_rotate_anim1);
            LinearInterpolator lin = new LinearInterpolator();//设置动画匀速运动
            animation.setInterpolator(lin);
            binding.playingLl.startAnimation(animation);
            // 播放状态变为播放时
            if (item.isOnlineMusic){
                Glide.with(mContext)
                        .load(thisImgUrl)
                        .placeholder(R.mipmap.hp_white_noise_fragment1_img4)
                        .error(R.mipmap.hp_white_noise_fragment1_img4)
                        .into(binding.playingImg);
            }
        }

        @Override
        public void onPause() {
            binding.playingLl.setVisibility(View.GONE);
            binding.playingLl.clearAnimation();
            // 播放状态变为暂停时
            /*btnPlayOrPause.setImageResource(R.drawable.bofang);
            btnPlayOrPause.setEnabled(true);*/
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        mContext.unbindService(mServiceConnection);
    }
}
